package com.erpoa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.erpoa.annotation.DataBase;
import com.erpoa.constants.DataSourceNames;
import com.erpoa.entity.DetallEnutiy;
import com.erpoa.entity.PackMessageByFlatStorage;
import com.erpoa.mapper.FlatStorageMapper;
import com.erpoa.service.FlatStorageService;
import com.erpoa.utils.FastJsonUtils;
import com.erpoa.utils.PDAException;
import com.erpoa.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author liuxinyong
 * @Title: FlatStorageServiceImpl
 * @ProjectName oaerp
 * @Description: TODO
 * @date 2021/1/1217:54
 */
@Service
public class FlatStorageServiceImpl  implements FlatStorageService {
    @Autowired
    private FlatStorageMapper flatStorageMapper;


    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<HashMap> querylistNo(String listNo) {

        //查询可以组盘的单号
        List<HashMap> list = flatStorageMapper.querylistNo(listNo);

        return list;

    }
    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<HashMap> querydetalt(String listNo) {

        //查询已组盘单号
        List<HashMap> list = flatStorageMapper.querydetalt(listNo);


        return list;

    }









    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public PackMessageByFlatStorage querypckBarcode(PackMessageByFlatStorage ByFlatStorage) {
        if(StringUtil.isEmpty(ByFlatStorage.getListNo())){
            throw new PDAException("单号不能为空，请确认！");
        }

        int wmsInList = flatStorageMapper.wmsInList(ByFlatStorage.getListNo());
        if(wmsInList==0){
            throw new PDAException("没有查到该单号，请确认单号是否正确！");
        }

        List<HashMap> mapList = this.querylineId(ByFlatStorage.getListNo());





        //根据条码查询带出明细
        PackMessageByFlatStorage messageByFlatStorages = flatStorageMapper.querypckBarcode(ByFlatStorage);
        if(StringUtil.isNull(messageByFlatStorages)){
            throw new PDAException("条码与预设单位的料号条码不一致，请确认！");
        }
        /*
         * 1.根据选择的单位转换成对应的单位的已组数量，未组数量并保存五位小数点
         * */
        Integer pckQty = flatStorageMapper.pckQty(messageByFlatStorages.getOrgNo(), messageByFlatStorages.getProdNo(), messageByFlatStorages.getPckUn());
        Integer hasCount=Integer.parseInt(messageByFlatStorages.getHasCount());
        Integer Nentered= Integer.parseInt(messageByFlatStorages.getQuantityNentered());
        float f  = (float) hasCount/pckQty;
        float  f1  = (float) Nentered/pckQty;
        BigDecimal b  =   new BigDecimal(f);
        BigDecimal b1  =   new BigDecimal(f1);
        float   f3   =  b.setScale(5, BigDecimal.ROUND_HALF_UP).floatValue();
        float   f4   =  b1.setScale(5, BigDecimal.ROUND_HALF_UP).floatValue();


        messageByFlatStorages.setHasCount(String.valueOf(f3));
        messageByFlatStorages.setQuantityNentered(String.valueOf(f4));


        return messageByFlatStorages;

    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<PackMessageByFlatStorage> querypckpackMessage(String listNo, String palletNo) {

        if(StringUtil.isEmpty(listNo)){
            throw new PDAException("单号不能为空");
        }
        List<PackMessageByFlatStorage> list=new ArrayList();
        if(StringUtil.isNotEmpty(palletNo)){
            //TODO
            List<PackMessageByFlatStorage> storages = flatStorageMapper.querypckpackMessage54(listNo,palletNo);
            if(StringUtil.isNotEmpty(storages)){
                list.addAll(storages);
            }else {
                PackMessageByFlatStorage pack=new PackMessageByFlatStorage();
                pack.setPalletNo("无");
                list.add(pack);
            }
            //TODO
            List<PackMessageByFlatStorage> storages32 = flatStorageMapper.querypckpackMessage(listNo,palletNo);
            if(StringUtil.isNotEmpty(storages32)){
                list.addAll(storages32);
            }
            return list;
        }else {
            //TODO
            List<PackMessageByFlatStorage> storages1 = flatStorageMapper.querypckpackMessage45(listNo);
            if(StringUtil.isNotEmpty(storages1)){
                list.addAll(storages1);
                return list;
               }

            }


          return list;


    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<HashMap> querypckUn(String prodNo, String orgNo) {
        if(StringUtil.isEmpty(prodNo)){
            throw new PDAException("料号不能为空");
        }
        if(StringUtil.isEmpty(orgNo)){
            throw new PDAException("货主不能为空");
        }
        //根据货主和单号查询单位
        List<HashMap> hashMaps = flatStorageMapper.querypckUn(prodNo,orgNo);
        if(StringUtil.isEmpty(hashMaps)){
            throw new PDAException("没有查到该货主的单位");
        }
        return hashMaps;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<HashMap> querylineId(String listNo) {
        if(StringUtil.isEmpty(listNo)){
            throw new PDAException("单号不能为空");
        }


        //查询项次
        List<HashMap> hashMaps = flatStorageMapper.querylineId(listNo);
        if(StringUtil.isEmpty(hashMaps)){
            throw new PDAException("该单号下的项次已组盘完成");
        }
        return hashMaps;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public PackMessageByFlatStorage querybyflat(PackMessageByFlatStorage ByFlatStorage) {
        if(StringUtil.isNull(ByFlatStorage.getListNo())){
            throw new PDAException("单号不能为空");
        }
        int wmsInList = flatStorageMapper.wmsInList(ByFlatStorage.getListNo());
        if(wmsInList==0){
            throw new PDAException("没有查到该单号，请确认单号是否正确！");
        }
        List<HashMap> mapList = this.querylineId(ByFlatStorage.getListNo());


        //根据单位和项次和料号查询
        PackMessageByFlatStorage querybyflat = flatStorageMapper.querybyflat(ByFlatStorage);
//        if(StringUtil.isNull(querybyflat)){
//            throw new PDAException("该单号下的项次已组完");
//        }
        /*
        * 1.根据选择的单位转换成对应的单位的已组数量，未组数量并保存五位小数点
        *
        * */

        Integer pckQty = flatStorageMapper.pckQty(querybyflat.getOrgNo(), querybyflat.getProdNo(), querybyflat.getPckUn());
        Integer hasCount=Integer.parseInt(querybyflat.getHasCount());
        Integer Nentered= Integer.parseInt(querybyflat.getQuantityNentered());
        float   f   = (float) hasCount/pckQty;
        float   f1   = (float) Nentered/pckQty;
        BigDecimal b  =   new BigDecimal(f);
        BigDecimal b1  =   new BigDecimal(f1);
        float   f3   =  b.setScale(5, BigDecimal.ROUND_HALF_UP).floatValue();
        float   f4   =  b1.setScale(5, BigDecimal.ROUND_HALF_UP).floatValue();

        querybyflat.setHasCount(String.valueOf(f3));
        querybyflat.setQuantityNentered(String.valueOf(f4));


        return querybyflat;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public JSONObject insert(PackMessageByFlatStorage packMessageByFlatStorage) {
        if(StringUtil.isEmpty(packMessageByFlatStorage.getListNo())){
            throw new PDAException("单号不能为空，请确认！");
        }
        if(StringUtil.isEmpty(packMessageByFlatStorage.getLineId())){
            throw new PDAException("项次不能为空，请确认！");
        }
        if(StringUtil.isEmpty(packMessageByFlatStorage.getProdNo())){
            throw new PDAException("料号不能为空，请确认！");
        }
        if(StringUtil.isEmpty(packMessageByFlatStorage.getProdName())){
            throw new PDAException("品名不能为空，请确认！");
        }
        if(StringUtil.isEmpty(packMessageByFlatStorage.getPltCount())){
            throw new PDAException("数量不能为空，请确认！");
        }
        if(StringUtil.isEmpty(packMessageByFlatStorage.getPalletNo())){
            throw new PDAException("托盘不能为空，请确认！");
        }
        if(StringUtil.isEmpty(packMessageByFlatStorage.getPckUn())){
            throw new PDAException("单位不能为空，请确认！");
        }
        JSONObject obj = new JSONObject();
        String selectuserId = flatStorageMapper.selectuserId(packMessageByFlatStorage);
        if(StringUtil.isEmpty(selectuserId)){
            throw new PDAException("没有查到当前用户ID，请联系IT管理员！");
        }
        packMessageByFlatStorage.setUserID(selectuserId);
        String count= packMessageByFlatStorage.getPltCount();
        String regex="^[1-9]+[0-9]*$";
        Pattern.compile(regex).matcher(count).find();
        if(Pattern.compile(regex).matcher(count).find()){
        }else {
            throw new PDAException("数量只能输正整数，请确认！");
        }
        int countflag1 = flatStorageMapper.countflag1(packMessageByFlatStorage.getListNo());
        if(countflag1>0){
            int countflag2 = flatStorageMapper.countflag2(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId());
            if(countflag2==1){
                int number1 = flatStorageMapper.number1(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId());
                if(number1==1){
                    throw new PDAException("该项次已组盘完成!");
                }
            }else {
                throw new PDAException("该项次不存在，请检查!");
            }
        }else {
            throw new PDAException("单号不存在或不符合组盘状态,请检查!");
        }
        Map param = new HashMap();
        param.put("psdcno","MG");
        param.put("fifono","");
        param.put("prcctr","");
        param.put("errcode","");
        param.put("errdesc","");

        String wms_genfifono_fc = this.flatStorageMapper.wms_genfifono_fc(param);
        Object fifono1 = param.get("fifono");
        DetallEnutiy detallEnutiy=new DetallEnutiy();
        Integer pltCount= Integer.parseInt(packMessageByFlatStorage.getPltCount());
        String pckUn=packMessageByFlatStorage.getPckUn();
        String listchar = flatStorageMapper.Listchar(packMessageByFlatStorage.getListNo());
        /**
         *
         * 校验PDA输入的托盘在组盘明细表WMS_IN_DETAIL中是否唯一,count(*)>0则报错
         * 校验库存是否存在该托盘数据 count(*)>0则报错
         *
         * */
        String selectdetail =flatStorageMapper.selectdetail(packMessageByFlatStorage.getPalletNo());
        String selectstk = flatStorageMapper.selectstk(packMessageByFlatStorage.getPalletNo());
        int selectdatai=Integer.parseInt(selectdetail);
        int selectst=Integer.parseInt(selectstk);
        if(selectdatai>0 && selectst>0){
            throw new PDAException("该托盘号"+packMessageByFlatStorage.getPalletNo()+"已存在");
        }else {
            //查询wms_in_line表中的单位
            String listQty = flatStorageMapper.selectqty(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo());
                if (pckUn.equals(listQty)) {
                    //转换成最小数量
                    String selecorgo = flatStorageMapper.selecorgo(packMessageByFlatStorage.getPckUn(), packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo());
                    int pckQty = Integer.parseInt(selecorgo);
                    int pltCOunt2 = pckQty * pltCount;
                    //查询wms_in_line表中可以存的数量
                    String selectnum = flatStorageMapper.selectnum(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getListNo());
                    if(StringUtil.isEmpty(selectnum)){
                        throw new PDAException("没有可以组盘的数量");
                    }
                    int quantity = Integer.parseInt(selectnum);
                    if (pltCOunt2 > quantity) {
                        throw new PDAException("超出可组盘数量");
                    }
                    String qty1 = String.valueOf(pltCOunt2);
                    //查询WMS_IN_LINE 表的tmp_qty
                    String selectTmpQTy = flatStorageMapper.selectTmpQTy(packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getListNo());
                    int listTmpQty = Integer.parseInt(selectTmpQTy);
                    //更新的WMS_IN_LINE 表的tmp_qty的数量
                    String upTmpQty = String.valueOf(listTmpQty + pltCOunt2);
                    //更新单身状态、数量：
                    int updateline = flatStorageMapper.updateline(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getProdNo(), upTmpQty);
                    //更新单头状态表：WMS_IN_LIST
                    int updatelist = flatStorageMapper.updatelist(packMessageByFlatStorage.getListNo());
                    if(!(updatelist>0)){
                        throw new PDAException("更新单头表失败，请联系管理员");
                    }

                    //同一项次，组盘数量累加
                    String palletidx = flatStorageMapper.palletidx(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getPalletNo(), packMessageByFlatStorage.getOrgNo());
                    if (StringUtil.isNotEmpty(palletidx)) {
                        int palletid = Integer.parseInt(palletidx) + 1;
                        palletidx = String.valueOf(palletid);
                    } else {
                        palletidx = "0";
                    }
                    //查询WMS_IN_list WMS_IN_line表中要插入WMS_IN_DETAIL表的数据
                    List<DetallEnutiy> enutiyList = flatStorageMapper.selectdetall(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getProdNo(), detallEnutiy);
                    if (StringUtil.isNotEmpty(enutiyList)) {
                        for (int j = 0; j < enutiyList.size(); j++) {
                            detallEnutiy = enutiyList.get(j);
                        }
                    } else {
                        throw new PDAException("插入失败，请联系管理员");
                    }
                    //查询lms_prod_pack_modle 表插入WMS_IN_DETAIL中的数据 pck_wgt
                    double pckWgt = flatStorageMapper.selectpckWgt(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getPckUn());

                    //箱数e净重字段
                    String pckWgt2 = String.valueOf(pltCount * pckWgt);
                    //序列号生成
                    String Groupid = flatStorageMapper.selectGroupid();
                    //插入明细表
                    int flatdetal = this.flatStorageMapper.insertDETAIL(packMessageByFlatStorage, detallEnutiy, palletidx, qty1, pckWgt2,fifono1,listchar);
                    if (!(flatdetal >0)) {
                        throw new PDAException("明细表插入失败，请联系管理员");
                    }
                    //插入预约表
                    int insertorder = flatStorageMapper.insertorder(packMessageByFlatStorage, detallEnutiy, palletidx, qty1, pckWgt2, fifono1, Groupid,listchar);
                    if(!(insertorder >0)){
                        throw new PDAException("预约表插入失败，请联系管理员");
                    }
                    //插入库存表
                    int insertStk = flatStorageMapper.insertStk(packMessageByFlatStorage, detallEnutiy, palletidx, qty1, pckWgt2,fifono1);
                    if(insertStk>0){
                        obj.put("success","组盘成功");
                    }else {
                        throw new PDAException("库存表插入失败，请联系管理员");
                    }
                } else {
                    //单位不一样的时候查询LMS_PROD_PACK_MODLE表中的单位进行判断
                    List<HashMap> mapList = flatStorageMapper.selectorgo(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getPckUn());
                    if (StringUtil.isNotEmpty(mapList)) {
                        //LMS_PROD_PACK_MODLE表中的pck_qty貨品包裝單位數量
                        int pckqty = Integer.parseInt(String.valueOf(mapList.get(0).get("PCKQTY")));
                        //LMS_PROD_PACK_MODLE表中的plt_count包裝/箱淨重
                        int pltcount =Integer.parseInt(String.valueOf(mapList.get(0).get("PLTCOUNT")));
                        //pltCount界面上数量
                        int num1 = pckqty * pltCount;//页面上要组盘数量（换成最小单位）
                        int num2 = pckqty * pltcount;//一站板最大数量（换成最小单位）
//                        if (num1 > num2) {
//                            throw new PDAException("超出一站板最多数量");
//                        }
                        //查询wms_in_line表中可以存的数量
                        String selectnum = flatStorageMapper.selectnum(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getListNo());
                        if(StringUtil.isEmpty(selectnum)){
                            throw new PDAException("没有可以组盘的数量");
                        }
                        int quantity = Integer.parseInt(selectnum);
//                           //查询wms_in_line表中的单位
//                          //TODO
//                           String listQty1 = flatStorageMapper.selectqty(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo());
//                           List<String> mapList2 = flatStorageMapper.selectorgo1(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), listQty1);
//                           int quantity = Integer.parseInt(mapList2.get(1));
//                           int num3 = quantity * pckqty;
                        if (num1 > quantity ) {
                            throw new PDAException("超出可入库数量");
                        }
                        String qty1 = String.valueOf(num1);
                        //查询WMS_IN_LINE 表的tmp_qty
                        String selectTmpQTy = flatStorageMapper.selectTmpQTy(packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getListNo());
                        int listTmpQty = Integer.parseInt(selectTmpQTy);
                        //更新的WMS_IN_LINE 表的tmp_qty的数量
                        String upTmpQty = String.valueOf(listTmpQty + num1);
                        //更新单身状态、数量：
                        flatStorageMapper.updateline(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getProdNo(), upTmpQty);
                        //更新单头状态表：WMS_IN_LIST
                        flatStorageMapper.updatelist(packMessageByFlatStorage.getListNo());
                        //同一项次，组盘数量累加
                        String palletidx = flatStorageMapper.palletidx(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getPalletNo(), packMessageByFlatStorage.getOrgNo());
                        if (StringUtil.isNotEmpty(palletidx)) {
                            int palletid = Integer.parseInt(palletidx) + 1;
                            palletidx = String.valueOf(palletid);
                        } else {
                            palletidx = "0";
                        }
                        //查询WMS_IN_list WMS_IN_line表中要插入WMS_IN_DETAIL表的数据
                        List<DetallEnutiy> enutiyList = flatStorageMapper.selectdetall(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getProdNo(), detallEnutiy);
                        if (StringUtil.isNotEmpty(enutiyList)) {
                            for (int j = 0; j < enutiyList.size(); j++) {
                                detallEnutiy = enutiyList.get(j);
                            }
                        } else {
                            throw new PDAException("插入失败，请联系管理员");
                        }
                        //查询lms_prod_pack_modle 表插入WMS_IN_DETAIL中的数据 pck_wgt
                        double pckWgt = flatStorageMapper.selectpckWgt(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getPckUn());
                        //箱数e净重字段
                        String pckWgt2 = String.valueOf(pltCount * pckWgt);
                        //序列号生成、
                        String Groupid = flatStorageMapper.selectGroupid();
                        //插入明细表
                        int flatdetal = this.flatStorageMapper.insertDETAIL(packMessageByFlatStorage, detallEnutiy, palletidx, qty1, pckWgt2,fifono1,listchar);
                        if (!(flatdetal >0)) {
                            throw new PDAException("明细表插入失败，请联系管理员");
                        }
                        //插入预约表
                        int insertorder = flatStorageMapper.insertorder(packMessageByFlatStorage, detallEnutiy, palletidx, qty1, pckWgt2, fifono1, Groupid,listchar);
                        if(!(insertorder >0)){
                            throw new PDAException("预约表插入失败，请联系管理员");
                        }
                        //插入库存表
                        int insertStk = flatStorageMapper.insertStk(packMessageByFlatStorage, detallEnutiy, palletidx, qty1, pckWgt2,fifono1);
                        if(insertStk>0){
                            obj.put("success","组盘成功");
                        }else {
                            throw new PDAException("库存表插入失败，请联系管理员");
                        }
                    }
                }
        }
        Integer pckQty = flatStorageMapper.pckQty(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getPckUn());
        float hasCount= Float.parseFloat(flatStorageMapper.selectnum(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getListNo()));
        float Nentered= Float.parseFloat(flatStorageMapper.selectTmpQTy(packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getListNo()));
        Integer pltcount = flatStorageMapper.pltcount(packMessageByFlatStorage.getOrgNo(), packMessageByFlatStorage.getProdNo(), packMessageByFlatStorage.getPckUn());
        float   f   = (float) hasCount/pckQty;
        float   f1   = (float) Nentered/pckQty;
        BigDecimal b  =   new BigDecimal(f);
        BigDecimal b1  =   new BigDecimal(f1);
        float   f3   =  b.setScale(5, BigDecimal.ROUND_HALF_UP).floatValue();
        float   f4   =  b1.setScale(5, BigDecimal.ROUND_HALF_UP).floatValue();

        String selectnum1 = String.valueOf(f3);
        String selectTmpQTy1 = String.valueOf(f4);
        obj.put("hasCount",selectTmpQTy1);
        obj.put("quantityNentered",selectnum1);
        if(f3<pltcount){
            int plcount=(int)f3;
            obj.put("pltCount",plcount);
        }else {
            obj.put("pltCount",pltcount);
        }


        return obj;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public JSONObject deletepalletNo(PackMessageByFlatStorage packMessageByFlatStorage) {

        int linecount = flatStorageMapper.selectlinecount1(packMessageByFlatStorage.getPalletNo());
        if(linecount>0){
            throw new PDAException("整单已组盘完成，不允许取消！");
        }
        int selectlinecount2 = flatStorageMapper.selectlinecount2(packMessageByFlatStorage.getPalletNo());
        if(selectlinecount2==0){
            throw new PDAException("该托盘已上架或订单状态不符合，不允许取消！");
        }
        String selectuserId = flatStorageMapper.selectuserId(packMessageByFlatStorage);
        if(StringUtil.isEmpty(selectuserId)){
            throw new PDAException("没有查到当前用户ID，请联系管理员！");
        }
        packMessageByFlatStorage.setUserID(selectuserId);
        PackMessageByFlatStorage JsonData = FastJsonUtils.getJsonToBean(packMessageByFlatStorage.getsName(),PackMessageByFlatStorage.class);
        //TODO
        packMessageByFlatStorage.setLineId(JsonData.getLineId());
        packMessageByFlatStorage.setListNo(JsonData.getListNo());

        JSONObject obj = new JSONObject();

        int fifono1 = flatStorageMapper.fifono1(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getPalletNo());
        if(fifono1>1){
            throw new PDAException("该托盘库存对应的FIFO_NO值异常，请联系IT管理员！");
        }
        //查询detail表fifo_no
        String fifono=flatStorageMapper.fifono(packMessageByFlatStorage.getListNo(),packMessageByFlatStorage.getLineId(),packMessageByFlatStorage.getPalletNo());

        //detail表组盘的数量
        String selectDealQty=flatStorageMapper.selectDealQty(packMessageByFlatStorage.getListNo(),packMessageByFlatStorage.getPalletNo());
        int dealQty=Integer.parseInt(selectDealQty);
        //line表组盘的数量
        String selectTmpQTy=flatStorageMapper.selectTmpQTy(packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getProdNo(),packMessageByFlatStorage.getListNo());
        int tmpQty=Integer.parseInt(selectTmpQTy);
        String tmpQty2=String.valueOf(tmpQty-dealQty);
        //更新入库单身表，回扣组盘量
        int updateWmsInLine1=flatStorageMapper.updateWmsInLine1(packMessageByFlatStorage.getListNo(),packMessageByFlatStorage.getLineId(),packMessageByFlatStorage,tmpQty2);
        if(!(updateWmsInLine1>0)){
            throw new PDAException("单身表更新失败，请联系管理员");
        }
        //根据条码查询 WMS_IN_DETAIL对应的的 pallet_Idx
        int pallet = Integer.parseInt(flatStorageMapper.selectPallet(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage.getPalletNo()));
        //根据单号查询 WMS_IN_DETAIL最大的 pallet_Idx
        int pallet1 = Integer.parseInt(flatStorageMapper.selectcountPallet(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId()));
        if(pallet==pallet1){
            //删除组盘库存
            int deleteWMSStk = flatStorageMapper.deleteWMS_STK(fifono);
            if(!(deleteWMSStk>0)){
                throw new PDAException("删除组盘库存失败，请联系管理员");
            }
            //删除入库预约
            int deleteWMSStkOrder = flatStorageMapper.deleteWMS_STK_ORDER(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), fifono);
            if(!(deleteWMSStkOrder>0)){
                throw new PDAException("删除入库预约失败，请联系管理员");
            }
            //删除组盘明细
            int deleteWMSInDetail = flatStorageMapper.deleteWMS_IN_DETAIL(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), fifono);
            if(!(deleteWMSInDetail>0)){
                throw new PDAException("删除组盘明细失败，请联系管理员");
            }
            //查询该单据，组盘删完没有
            int countnum=flatStorageMapper.countnum(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(),packMessageByFlatStorage.getProdNo());
            if(countnum==0){
                //修改单身表
                int updatewmsInline = flatStorageMapper.updatewmsInline(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage);
                if(!(updatewmsInline>0)){
                    throw new PDAException("更新单身表失败，请联系管理员");
                }
                //修改单头表
                int updatewmsInlist = flatStorageMapper.updatewmsInlist(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage);
                if(!(updatewmsInlist>0)){
                    throw new PDAException("更新单头表失败，请联系管理员");
                }else {
                    obj.put("sucess","取消组盘成功");
                }
            } else {
                //修改单身表
                int updatewmsInline2 = flatStorageMapper.updatewmsInline2(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage);
                if(!(updatewmsInline2>0)){
                    throw new PDAException("更新单身表失败，请联系管理员");
                }
                //修改单头表
                int updatewmsInlist = flatStorageMapper.updatewmsInlist1(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage);
                if(!(updatewmsInlist>0)){
                    throw new PDAException("更新单头表失败，请联系管理员");
                }else {
                    obj.put("success","取消组盘成功");
                }
            }
        }
        else {
            //更新入库明细表托数序号
            int updatedatalt= flatStorageMapper.upadtedetalt(packMessageByFlatStorage.getListNo(),packMessageByFlatStorage.getLineId(),packMessageByFlatStorage,pallet);
            if(!(updatedatalt>0)){
                throw new PDAException("更新入库明细表失败，请联系管理员");
            }
            //删除组盘库存
            int deleteWMSStk = flatStorageMapper.deleteWMS_STK(fifono);
            if(!(deleteWMSStk>0)){
                throw new PDAException("删除组盘库存失败，请联系管理员");
            }
            //删除入库预约
            int deleteWMSStkOrder = flatStorageMapper.deleteWMS_STK_ORDER(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), fifono);
            if(!(deleteWMSStkOrder>0)){
                throw new PDAException("删除入库预约失败，请联系管理员");

            }
            //删除组盘明细
            int deleteWMSInDetail = flatStorageMapper.deleteWMS_IN_DETAIL(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), fifono);
            if(!(deleteWMSInDetail>0)){
                throw new PDAException("删除组盘明细失败，请联系管理员");
            }
            //查询该单据，组盘删完没有
            int countnum=flatStorageMapper.countnum(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(),packMessageByFlatStorage.getProdNo());
            if(countnum==0){
                //修改单身表
                int updatewmsInline = flatStorageMapper.updatewmsInline(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage);
                if(!(updatewmsInline>0)){
                    throw new PDAException("更新单身表失败，请联系管理员");
                }
                //修改单头表
                int updatewmsInlist = flatStorageMapper.updatewmsInlist(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage);
                if(!(updatewmsInlist>0)){
                    throw new PDAException("更新单头表失败，请联系管理员");
                }else {
                    obj.put("sucess","取消组盘成功");
                }
            }else{
                //修改单身表
                int updatewmsInline2 = flatStorageMapper.updatewmsInline2(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage.getLineId(), packMessageByFlatStorage);
                if(!(updatewmsInline2>0)){
                    throw new PDAException("更新单身表失败，请联系管理员");
                }
                //修改单头表
                int updatewmsInlist = flatStorageMapper.updatewmsInlist1(packMessageByFlatStorage.getListNo(), packMessageByFlatStorage);
                if(!(updatewmsInlist>0)){
                    throw new PDAException("更新单头表失败，请联系管理员");
                }else {
                    obj.put("success","取消组盘成功");
                }
            }
        }

        return obj;
    }






    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public PackMessageByFlatStorage groundQueryDetailByPalletNo(PackMessageByFlatStorage packMessage) {
        if (StringUtil.isEmpty(packMessage.getPalletNo())) {
            throw new PDAException("托盘号不能为空，请确认！");
        }

         /*  -- 0 接单
                --12 入库中
                --14 组盘完成
                --16 已入库
                ---90 结案
                --上架前校验是否已组盘完成
        select * from WMS_IN_LIST t where LIST_NO='MGGI12100000004' and STATUS_CTR >= 14 and STATUS_CTR<90;*/
       /*
        String  statusDtr =   this.flatStorageMapper.checkHasGroupByPalletNo(packMessage.getPalletNo());
        if (StringUtil.isNotEmpty(statusDtr)){
            throw new PDAException("当前托盘号单号明细未完成组盘,状态码为："+statusDtr+",请确认");
        }*/

      /*  ---校验PDA输入的托盘在组盘明细表WMS_IN_DETAIL中是否唯一,count(*)>0 则报错（Z5555为PDA界面托盘号)
        select count(*) from WMS_IN_DETAIL t left join WMS_STK t1 on t.fifo_no=t1.fifo_no
        where ((t.PALLET_NO='Z5555' and t.fifo_sts_ctr=0) or t1.PALLET_NO='Z5555' );*/


        //TODO CJM
        int detailunique = this.flatStorageMapper.countdetailByPalletNo(packMessage.getPalletNo());
        if (detailunique != 1) {
            throw new PDAException("当前托盘已上架或托盘不存在,请联系相关人员确认数据准确性！");
        }



/*
        ---校验库存是否存在该托盘数据 count(*)>0则报错
        select count(*) from WMS_STK t
        where t.PALLET_NO='Z5555' ;*/
        int stkcount = this.flatStorageMapper.countStkByPalletNo(packMessage.getPalletNo());

        if (stkcount > 0) {
            throw new PDAException("该托盘库存已存在库存中,请联系相关人员确认数据准确性！");
        }


        PackMessageByFlatStorage detailPallet = this.flatStorageMapper.selectDetailByPalletNo(packMessage.getPalletNo());
        if (StringUtil.isNull(detailPallet)) {
            throw new PDAException("当前托盘号：" + packMessage.getPalletNo() + "，未组盘完成，请确认！");
        }

        return detailPallet;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public String groundQueryAreaNoByPalletNo(PackMessageByFlatStorage packMessage) {

        if (StringUtil.isEmpty(packMessage.getBinCode())) {
            throw new PDAException("储区不能为空，请确认！");
        }
        /*--校验PDA输入的储位是否存在，count(*)= 0 ,则报错，以及该储位已存放两坨以上托盘,count(*)>1,则报错（A3600207为PDA界面储位）
        select count(*) from WMS_BIN where BIN_CODE='A3600207';
        select count(*) from WMS_STK where BIN_CODE='A3600207';*/
        Integer countBin = this.flatStorageMapper.queryBinByBarCode(packMessage.getBinCode());
        if (countBin == null) {
            throw new PDAException("当前储区不存在，请确认！");
        }
        if (countBin == 0) {
            throw new PDAException("当前储区没有可用储位，请确认！");
        }

        //TODO
        String inhibitInFlgfrom = this.flatStorageMapper.inhibit_in_flgfrom(packMessage.getBinCode());
        if("y".equals(inhibitInFlgfrom) ){
            throw new PDAException("该储位已被禁用,请联系相关人员确认数据准确性！");
        }
//        int countStk = this.flatStorageMapper.queryStkByBarCode(packMessage.getBinCode());
//        if (countStk > 1) {
//            throw new PDAException("当前储区已满，请确认！");
//        }
        JSONObject obj = new JSONObject();
        obj.put("45", "成功！");
        return JSONObject.toJSONString(obj);
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public String groundUpdateDetailByPalletNo(PackMessageByFlatStorage packMessage) {

        PackMessageByFlatStorage detail = this.groundQueryDetailByPalletNo(packMessage);

        String areaNo = this.groundQueryAreaNoByPalletNo(packMessage);

        detail.setPalletNo(packMessage.getPalletNo());
        detail.setBinCode(packMessage.getBinCode());
        Map param = new HashMap();
        param.put("fifoNo", detail.getFifoNo());
        param.put("un", detail.getUn());
        param.put("qty", detail.getQty());
        param.put("binCode", detail.getBinCode());
        param.put("palletNo", detail.getPalletNo());
        param.put("palletNo", detail.getPalletNo());
        param.put("remark", "45");
        param.put("sCode", Integer.valueOf(packMessage.getUser().getsCode()));
        param.put("result1", "");
        param.put("result2", "");
        param.put("result", "");
        param.put("result3", "");
        param.put("result4", "");
        param.put("result5", "");
        String resiltwms = this.flatStorageMapper.callWMS_ASRS_FINISH_I_1_FC(param);

        if ("0".equals(param.get("result").toString())) {
            if (StringUtil.isNotNull(param.get("result3"))) {
                throw new PDAException("上架失败，原因：" + param.get("result3") + "，请确认！")

                        ;
            } else {
                throw new PDAException("上架失败，请确认！");
            }
        }
        JSONObject object = new JSONObject();
        object.put("success", "成功");
        return JSONObject.toJSONString(object);
    }



    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<PackMessageByFlatStorage> qureyLINE(PackMessageByFlatStorage packMessageByFlatStorage) {
        if(StringUtil.isNotEmpty(packMessageByFlatStorage.getListNo())){
            return this.flatStorageMapper.querywmsInline(packMessageByFlatStorage.getListNo());
        }else {
            throw new PDAException("单号不能为空");
        }
    }




    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<HashMap> selectAreaListByParam(PackMessageByFlatStorage packMessage) {
        if (StringUtil.isEmpty(packMessage.getPickDate())) {
            throw new PDAException("请先选择日期，请确认！");
        }
        List<HashMap> areaList = this.flatStorageMapper.selectAreaListByParam(packMessage.getPickDate());
        if (StringUtil.isEmpty(areaList)) {
            throw new PDAException("未拉取到任何储区，请确认！");
        }
        return areaList;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<HashMap> selectSnameListByParam(PackMessageByFlatStorage packMessage) {
        if (StringUtil.isEmpty(packMessage.getPickDate())) {
            throw new PDAException("请先选择日期，请确认！");
        }
        if (StringUtil.isEmpty(packMessage.getSrcAreaNo())) {
            throw new PDAException("请先选择储区，请确认！");
        }
        List<HashMap> sNameList = this.flatStorageMapper.selectSnameListByParam(packMessage);
        if (StringUtil.isEmpty(sNameList)) {
            throw new PDAException("未拉取到任何客户，请确认！");
        }
        return sNameList;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<PackMessageByFlatStorage> selectOutListByParam(PackMessageByFlatStorage packMessage) {
        if (StringUtil.isEmpty(packMessage.getPickDate())) {
            throw new PDAException("请先选择日期，请确认！");
        }
        if (StringUtil.isEmpty(packMessage.getSrcAreaNo())) {
            throw new PDAException("请先选择储区，请确认！");
        }
      /*  List<HashMap> sNameList = this.flatStorageMapper.selectSnameListByParam(packMessage);
        if (StringUtil.isEmpty(sNameList)){
            throw new PDAException("未拉取到任何客户，请确认！");
        }*/

        List<PackMessageByFlatStorage> outList = this.flatStorageMapper.selectOutListBy(packMessage);
        if (StringUtil.isEmpty(outList)) {
            throw new PDAException("未拉取到任何出库列表数据，请确认！");
        }

        ArrayList list = new ArrayList();
        for(int i=0;i<=outList.size();i++){
            PackMessageByFlatStorage p = new PackMessageByFlatStorage();
        }
        System.out.println(JSONObject.toJSONString(outList));
        return outList;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public PackMessageByFlatStorage checkProdNoBypckCode(PackMessageByFlatStorage packMessage) {
        if (StringUtil.isEmpty(packMessage.getProdNo())) {
            throw new PDAException("打印界面没有料号，请重新打开界面！");
        }
        if (StringUtil.isEmpty(packMessage.getPckBarCode())) {
            throw new PDAException("外箱码不正确，请重新扫描！");
        }
        if (StringUtil.isEmpty(packMessage.getOrgNo())) {
            throw new PDAException("货主不存在，请重新打开界面！");
        }
        String prodNoTemp = this.flatStorageMapper.selectProdByPackBarCode(packMessage);
        if (!packMessage.getProdNo().equals(prodNoTemp)) {
            throw new PDAException("当前料号与外箱码不匹配，请确认！");
        }
        packMessage.setProdName(packMessage.getProdNo());
        packMessage.setProdNo(prodNoTemp);

        return packMessage;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public List<PackMessageByFlatStorage> insertOut(PackMessageByFlatStorage packMessage) {

        if (StringUtil.isEmpty(packMessage.getProdNo())) {
            throw new PDAException("打印界面没有料号，请重新打开界面！");
        }

        if (StringUtil.isEmpty(packMessage.getPickListNo())) {
            throw new PDAException("当前集单号不存在，请重新打开界面！");
        }
        if (StringUtil.isEmpty(packMessage.getBinCode())) {
            throw new PDAException("当前库位不存在，请重新打开界面！");
        }
        if (StringUtil.isEmpty(packMessage.getSrcQtyDesc())) {
            throw new PDAException("当前数量不存在，请重新打开界面！");

        }
        if (StringUtil.isEmpty(packMessage.getCustNo())) {
            throw new PDAException("当前客户不存在，请重新打开界面！");

        }
        if (StringUtil.isEmpty(packMessage.getOrgNo())) {
            throw new PDAException("当前货主不存在，请重新打开界面！");

        }

/*
        List<PackMessageByFlatStorage> asrsFinishs = this.flatStorageMapper.queryAsrsFinishList(packMessage);


        if (StringUtil.isEmpty(asrsFinishs)) {
            throw new PDAException("当前集单号未拉取到相对应数据，请确认！");
        }

        ArrayList<PackMessageByFlatStorage> lists = new ArrayList<>();
        int countTemp =  this.insertOutTemp(asrsFinishs,packMessage);*/

        //查询出库标签
        List<PackMessageByFlatStorage> packMessageByFlatStoragetemps = this.flatStorageMapper.queryPrintData(packMessage);


        if (StringUtil.isEmpty(packMessageByFlatStoragetemps)) {
           throw new PDAException("出库数据已打印或已打印过！");
        }


        return packMessageByFlatStoragetemps;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public List<PackMessageByFlatStorage> selectOutList(PackMessageByFlatStorage packMessage) {
        //查询出库标签
        List<PackMessageByFlatStorage> packMessageByFlatStoragetemps = this.flatStorageMapper.queryPrintData(packMessage);


        if (StringUtil.isEmpty(packMessageByFlatStoragetemps)) {
             throw new PDAException("未拉取到出库标签，请确认！");
        }


        return packMessageByFlatStoragetemps;
    }



    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int insertOutTemp(List<PackMessageByFlatStorage> asrsFinishs,PackMessageByFlatStorage packMessage) {
        int count = 0;
        for (PackMessageByFlatStorage asrsFinish : asrsFinishs) {
            Map param = new HashMap();
            param.put("listNo", asrsFinish.getPickListNo());
            param.put("lineId", asrsFinish.getLineId());
            param.put("fifoNo", asrsFinish.getFifoNo());
            param.put("un", asrsFinish.getUn());
            param.put("qty", asrsFinish.getQty());
            param.put("srcBinCode", asrsFinish.getSrcBinCode());
            param.put("palletNo", asrsFinish.getPalletNo());
            param.put("dfbType", "N");
            param.put("remark", "45");
            param.put("sCode", Integer.valueOf(packMessage.getUser().getsCode()));
            param.put("result1", "");
            param.put("result2", "");
            param.put("result", "");
            param.put("result3", "");
            String hj = this.flatStorageMapper.callWMSRSFINISHO2FC(param);

            if ("0".equals(param.get("result").toString())) {
                //TODO CJM
             /*   if (StringUtil.isNotNull(param.get("result3"))) {
                    throw new PDAException("出库失败，原因：" + param.get("result3") + ",请确认！");
                } else {
                    throw new PDAException("出库失败，请确认！");
                }*/
            }
            count++;
        }
        return count;
    }

    @Override
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public JSONObject updateAutoPrint(PackMessageByFlatStorage packMessage) {

        JSONObject obj = new JSONObject();
        int autoPrint = flatStorageMapper.updateAutoPrint(packMessage);
        if(autoPrint>0){
            obj.put("success", "成功");
        }else {
            throw new PDAException("失败");
        }
        return obj;
    }
}
